import {Cartographic, Math as cesiumMath} from 'cesium'

/**
 * 查询地图范围
 */
export function queryMapRange() {
    const camera = viewer.scene.camera
    const cameraPosiion = camera.position
    const cartographic = Cartographic.fromCartesian(cameraPosiion)
    const longitude = cesiumMath.toDegrees(cartographic.longitude)
    const latitude = cesiumMath.toDegrees(cartographic.latitude)
    const height = cartographic.height
    let size = calculateSizeFromHeight(height)
    let zoom = calculateZoomFromHeight(height)
    //方向   围绕Z轴旋转
    const heading = cesiumMath.toDegrees(camera.heading).toFixed(2);
    //倾斜角度   围绕Y轴旋转
    const pitch = cesiumMath.toDegrees(camera.pitch).toFixed(2);
    //围绕X轴旋转
    const roll = cesiumMath.toDegrees(camera.roll).toFixed(2);
    return {longitude, latitude, size, zoom, height, heading, pitch, roll}
}

/**
 * 根据给定的场景高度计算地图中显示范围的宽度
 * @param height 场景高度
 * @returns {number} 地图显示范围尺寸
 * @private
 */
export function calculateSizeFromHeight(height) {
    var _PI = 3.1415926
    var _earthRadius = 6378137
    var size
    if (height >= _earthRadius) {
        // 当场景高度大于可全幅显示整球的高度时
        var ratio = (height + _earthRadius) * 0.5
        size = 120 * ratio / _earthRadius
    } else {
        // 当场景高度小于可全幅显示整球的高度时，即无法看到整球时
        var tan30 = Math.tan(_PI / 6)
        // 设置方程组的a,b,c
        var a = (Math.pow(tan30, 2) + 1) * Math.pow(_earthRadius, 2)
        var b = -2 * (_earthRadius + height) * _earthRadius * Math.pow(tan30, 2)
        var c = Math.pow(tan30, 2) * Math.pow(_earthRadius + height, 2) - Math.pow(_earthRadius, 2.0)
        // 解一元二次方程，取锐角，因此余弦值较大
        var cosd = (-b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a)
        var d = Math.acos(cosd)
        var widthd = 2 * d * _earthRadius
        size = (widthd / (_PI * _earthRadius)) * 180
    }
    return size
}

/**
 * 根据给定的场景高度计算地图近似的层级
 * @param height
 */
export function calculateZoomFromHeight(height) {
    var A = 40487.57;
    var B = 0.00007096758;
    var C = 91610.74;
    var D = -40467.74;
    return Math.round(D + (A - D) / (1 + Math.pow(height / C, B)));
}
